package com.yazi.mxz.common.db.dao.impl;


import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.hibernate.dao.BasicDao;
import com.yazi.mxz.common.db.dao.MemberPrepaidDao;
import com.yazi.mxz.common.entity.beans.Company;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.MemberPrepaid;
import com.yazi.mxz.common.entity.custom.MemberPrepaid4Search;

@Repository("memberPrepaidDao")
public class MemberPrepaidDaoImpl extends BasicDao<MemberPrepaid> implements MemberPrepaidDao {


	public MemberPrepaidDaoImpl() {
		super(MemberPrepaid.class);
		
	}

	@Override
	public Criteria getExample(MemberPrepaid mp, String searchWord) {
		Criteria c = super.getExample(mp, searchWord);
		
		// 关联对象条件
		if (null != mp) {
			// 企业
			Company company = mp.getCompany();
			if (null !=  company) {
				// 企业ID
				if (null != company.getCompanyId()) {
					c.add(Restrictions.eq("company.companyId", company.getCompanyId()));
				} else {
					// ...企业其它条件
				}
			}
			// 用户
			Member member = mp.getMemberByMemberId();
			if (null !=  member) {
				// 用户ID
				if (null != member.getMemberId()) {
					c.add(Restrictions.eq("memberByMemberId.memberId", member.getMemberId()));
				} else {
					// ...用户其它条件
				}
			}
			// ...其它关联对象条件
		}
		
		// 关键字条件
		if(null != searchWord && !searchWord.isEmpty()){
			c.createAlias("memberByMemberId", "member");
			//关键字可查用户名、邮箱、手机号
			String likeWord = "%" + searchWord + "%";
			c.add(Restrictions.or(
					Restrictions.like("member.name", likeWord),
					Restrictions.or(Restrictions.like("member.email", likeWord),
							Restrictions.like("member.mobile", likeWord))));
		}
		
		return c;
	}
	
	@Override
	public Page<MemberPrepaid> list(MemberPrepaid4Search mp4s, Searching si) {
		Criteria c = getCriteria(mp4s, si.getSearchWord());
		return list(c, si);
	}
	
	private Criteria getCriteria(MemberPrepaid4Search mp4s, String searchWord) {
		Criteria c = getExample(mp4s, searchWord);
		// 时间范围
		if (null != mp4s.getStartTime() && null != mp4s.getEndTime()) {
			c.add(Restrictions.between("addTime", mp4s.getStartTime(), mp4s.getEndTime()));
	
		} // 大于某个时间 
		else if (null != mp4s.getStartTime()) {
			c.add(Restrictions.gt("addTime", mp4s.getStartTime()));
			
		} // 小于某个时间
		else if (null != mp4s.getEndTime()) {
			c.add(Restrictions.lt("addTime", mp4s.getEndTime()));
		}
		return c;
	}
}
